﻿namespace Pibby.Core.IO
{
	using System.IO;

	public class FileSystemDriveFactory : IDriveFactory
	{
		public IDriveCollection GetAllDrives()
		{
			IDriveCollection allDrives = new IDriveCollection();

			DriveInfo[] driveList = DriveInfo.GetDrives();

			foreach (var drive in driveList)
			{
				try
				{
					allDrives.Add(new FileSystemDrive(drive.Name));
				}
				catch (System.IO.IOException)
				{
					// may be trying to connect to drives that are not ready - swallow this exception
				}
			}

			return allDrives;
		}

		public IDrive GetDriveByName(string name)
		{
			DriveInfo[] driveList = DriveInfo.GetDrives();

			foreach (var drive in driveList)
			{
				try
				{
					if (drive.Name == name)
					{
						return new FileSystemDrive(drive.Name);
					}
				}
				catch (System.IO.IOException)
				{
					// may be trying to connect to drives that are not ready - swallow this exception
				}
			}

			return null;
		}

		public IDrive GetDriveByLabel(string volumeLabel)
		{
			DriveInfo[] driveList = DriveInfo.GetDrives();

			foreach (var drive in driveList)
			{
				try
				{
					if (drive.IsReady && drive.VolumeLabel == volumeLabel)
					{
						return new FileSystemDrive(drive.Name);
					}
				}
				catch (System.IO.IOException)
				{
					// may be trying to connect to drives that are not ready - swallow this exception
				}
			}

			return null;
		}
	}
}
